package com.atguigu.gmall.order.intercepter;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/***
 * 订单微服务自定义拦截器
 */
@Component
public class OrderIntercepter implements RequestInterceptor {

    /**
     * 拦截逻辑
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ////获取原request相关的请求包装对象: 原请求有的情况下才有HttpServletRequest,不是http请求触发的,将为null
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes == null){
            return;
        }

        //获取到从网关来的请求对象
        HttpServletRequest request = requestAttributes.getRequest();

        //获取到所有请求头的name
        Enumeration<String> headerNames = request.getHeaderNames();
        //遍历
        while (headerNames.hasMoreElements()){
            //获取到每个名字
            String name = headerNames.nextElement();
            //获取到每个请求头中name对应的value
            String value = request.getHeader(name);

            //把网关中请求头的中内容，复制到requestTemplate的请求头中
            requestTemplate.header(name,value);
        }
    }
}
